<?php

namespace app\agent\controller;

use app\admin\model\Admin;
use app\common\controller\Agent;
use app\common\model\AgentMoneyRecord;
use app\common\model\Bank;
use app\common\model\Images;
use app\common\model\Message;
use app\common\model\OrderAftersalesRecord;
use think\Db;
use think\Exception;
use think\Queue;

/**
 * 资金明细
 *
 * @icon fa fa-user
 */
class WithdrawalRecord extends Agent
{

    protected $relationSearch = true;
    protected $multiFields = 'status';

    protected $model = null;
    protected $agent_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('AgentWithdrawalRecord');
        $agent_info = session('agent');
        $this->agent_id = $agent_info['id'];
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model->with(['bank'])->where($where)->where(['agent_id'=>$this->agent_id])->order($sort, $order)->paginate($limit);
            if (empty($filter['status'])) { //全统计
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',1)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//待审核总额
                $success_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',2)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//审核成功总额
                $fail_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',3)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//审核失败总额
            }elseif ($filter['status'] == 1){
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',1)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = $money_amount;
                $success_amount = 0;
                $fail_amount = 0;
            }elseif ($filter['status'] == 2){
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',2)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = 0;
                $money_amount = $money_amount;
                $success_amount = 0;
                $fail_amount = 0;
            }elseif ($filter['status'] == 3){
                $money_amount = $this->model->with(['bank','agent'])->where($where)->where('agent_withdrawal_record.status',3)->where(['agent_id'=>$this->agent_id])->sum('agent_withdrawal_record.money');//总提现金额
                $wait_amount = 0;
                $success_amount = 0;
                $fail_amount = $money_amount;
            }
            $count = [['name'=>'总提现金额','value'=>sprintf("%.3f",$money_amount)],['name'=>'审核失败总额','value'=>sprintf("%.3f",$fail_amount)],['name'=>'审核成功总额','value'=>sprintf("%.3f",$success_amount)],['name'=>'待审核总额','value'=>sprintf("%.3f",$wait_amount)]];
            $result = array("total" => $list->total(), "rows" => $list->items(),'extend'=>['count'=>$count]);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 新增提现
     */
    public function add()
    {
        $agent_info = \app\agent\model\Agent::get($this->agent_id);

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $balance = $agent_info['money'] - $params['money'];
                    if ($balance < 0){
                        exception('提现金额不能大于账户余额');
                    }
                  //提交的资料
                    if ($params['method'] == 1){
                        $arr = ['money'=>$params['money'],'balance'=>$balance,'agent_id'=>$this->agent_id,'method'=>$params['method'],'account_name'=>$params['account_name'],'bank_id'=>$params['bank_id'],'account'=>$params['account'],'remark'=>$params['remark']];
                    }else{
                        if ($params['money'] >500)
                            exception('提现金额不能大于500元');
                        if ($params['money'] <0.3)
                            exception('提现金额不能小于0.3元');
                        $arr = ['money'=>$params['money'],'balance'=>$balance,'agent_id'=>$this->agent_id,'method'=>$params['method'],'remark'=>$params['remark']];
                    }
                    AgentMoneyRecord::create(['type'=>3,'money'=>$params['money'],'balance'=>$balance,'order_id'=>'','agent_id'=>$this->agent_id,'createtime'=>time()]);//提现
                    \app\common\model\Agent::update(['money'=>$balance],['id'=>$this->agent_id]);
                    $this->model->save($arr);
                    Message::create(['content'=>"代理商：".$agent_info['username'].',发起一笔提现申请']);//发送站内信
                    Db::commit();
                    $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
                    foreach ($admins as $v){
                        Queue::push(\app\job\Message::class,[
                            'member_id'=>$v['member_id'],
                            'template_id'=>config('wechat_gzh')['gzh_template']['tixian_audit'],
                            'data'=>[
                                'time1'=>date('Y-m-d'),
                                'amount2'=>$params['money'],
                                'thing3'=>"代理商：".$agent_info['username']
                            ]
                        ],'message');
                    }
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = Bank::all();
        $temp[] = '请选择所属银行';
        foreach ($list as $item){
            $temp[$item['id']] = $item['bank_name'];
        }
        $this->view->assign("list", $temp);
        $this->view->assign("balance", $agent_info->money);
        return $this->view->fetch();
    }



}
